<?php

/**
 * 跨域解决方案
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnableCrossRequestMiddleware
{
    /**
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
		if ($response instanceof \Illuminate\Http\Response) {
			$response->header('Access-Control-Allow-Origin', '*');
			$response->header('Access-Control-Allow-Headers', '*');
			$response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
			$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
			$response->header('Access-Control-Max-Age', 172800);
			$response->header('Access-Control-Allow-Credentials', 'true');
		} else {
			$response->headers->set('Access-Control-Allow-Origin', '*');
			$response->headers->set('Access-Control-Allow-Headers', '*');
			$response->headers->set('Access-Control-Expose-Headers', 'Authorization, authenticated');
			$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
			$response->headers->set('Access-Control-Max-Age', 172800);
			$response->headers->set('Access-Control-Allow-Credentials', 'true');
		}
        return $response;
    }
}
